import express from 'express';
import {
  generateExamQuestion,
  recordWrongQuestion,
  getWrongQuestions,
  generateFromWrongQuestions
} from '../services/exam-review';

const router = express.Router();

// 获取指定类型题目
router.get('/question/:typeId', (req, res) => {
  try {
    const { typeId } = req.params;
    const difficulty = parseInt(req.query.difficulty as string) || 1;
    const question = generateExamQuestion(typeId, difficulty);
    res.json(question);
  } catch (err: unknown) {
    // 处理未知类型的错误
    const errorMessage = err instanceof Error ? err.message : 'Unknown error';
    res.status(400).json({ error: errorMessage });
  }
});

// 提交答案并记录错题
router.post('/submit', (req, res) => {
  try {
    const { studentId, question, isCorrect } = req.body;
    if (!isCorrect) {
      recordWrongQuestion(studentId, question);
    }
    res.json({ success: true });
  } catch (err: unknown) {
    // 处理未知类型的错误
    const errorMessage = err instanceof Error ? err.message : 'Unknown error';
    res.status(400).json({ error: errorMessage });
  }
});

// 获取错题
router.get('/wrong-questions/:studentId', (req, res) => {
  try {
    const { studentId } = req.params;
    const questions = getWrongQuestions(studentId);
    res.json(questions);
  } catch (err: unknown) {
    // 处理未知类型的错误
    const errorMessage = err instanceof Error ? err.message : 'Unknown error';
    res.status(400).json({ error: errorMessage });
  }
});

// 从错题生成新题目
router.get('/wrong-question/:studentId', (req, res) => {
  try {
    const { studentId } = req.params;
    const question = generateFromWrongQuestions(studentId);
    res.json(question || { message: 'No wrong questions' });
  } catch (err: unknown) {
    // 处理未知类型的错误
    const errorMessage = err instanceof Error ? err.message : 'Unknown error';
    res.status(400).json({ error: errorMessage });
  }
});

export default router;